package com.xiaoy.util.format;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import com.xiaoy.util.store.io.ReadFileUtil;




public class FileUtil {
	
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	
	private final static String reg = "[*/?:><|\\\\]";


	/**
	 * 得到classes下的文件流
	 * @param name
	 * @return
	 */
	public static InputStream getInputStram (String filename) {
		return FileUtil.class.getClassLoader().getResourceAsStream(filename);
	}
	
	public static InputStream getInputStramByAbs (String filename) throws FileNotFoundException {
		return new FileInputStream(new File(filename));
	}
	/**
	 * 得到classes下的文件绝对路径
	 * @param name
	 * @return
	 */
	public static String getPath (String filename) {
//		System.out.println("filename-->"+filename);
//		System.out.println(FileUtil.class.getClassLoader().getResource(filename));
		return  FileUtil.class.getClassLoader().getResource(filename).getPath();
	}
	
	/**
	 * 读取文件的内容
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static String read (String filename) throws IOException {
		
//		InputStream is = new FileInputStream(new File(getPath(filename)));
		
		InputStream is = getInputStram(filename);
		StringBuffer result = new StringBuffer();
		if (is != null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
			String temp = "";
			while ((temp = reader.readLine()) != null) {
				result.append(temp+"\n");
			}
		}
		return result.toString();
	}

	public static void wirte (String path,String filename,InputStream content ) throws IOException{
		
		File f = new File(path);
		if (!f.exists()){
			f.mkdirs();
		}
		File filename_temp = new File(path,filename); 
		filename_temp.createNewFile(); 
		
		FileOutputStream fileOut = new FileOutputStream(filename_temp);
		
		if (content!=null){
			int c = 0;
			while ((c=content.read())!=-1) {
				fileOut.write(c);
			}
			fileOut.flush();
			fileOut.close();
		}
	}
	
	public static void main(String[] args) {
		
		try {
			wirte("c:/","test.txt",new ByteInputStream("nimeidea".getBytes(),10000));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void wirte (String path,String filename,String content ) throws IOException {

		File f = new File(path);
		if (!f.exists()){
			f.mkdirs();
		}
		File filename_temp = new File(path,filename); 
		filename_temp.createNewFile(); 
		
		PrintStream printStream = new PrintStream(new FileOutputStream(filename_temp));
//		System.out.println(filename_temp.getPath());
	    printStream.println(content);//将字符串写入文件
	    printStream.flush();
	    printStream.close();
	    printStream=null;
	}
	
	/**
	   * 删除某个文件夹下的所有文件夹和文件
	   * @param delpath String
	   * @throws FileNotFoundException
	   * @throws IOException
	   * @return boolean
	   */
	public static boolean deleteDir(String delpath) throws FileNotFoundException, IOException {
		try {
			File file = new File(delpath);
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "\\" + filelist[i]);
					if (!delfile.isDirectory()) {
						delfile.delete();
					} else if (delfile.isDirectory()) {
						deleteDir(delpath + "\\" + filelist[i]);
					}
				}
				file.delete();
			}
		} catch (FileNotFoundException e) {
			logger.debug(e.getMessage());
		}
		return true;
	}
	
	/**
	   * 读取某个文件夹下的所有文件夹和文件
	   * @param delpath String
	   * @throws FileNotFoundException
	   * @throws IOException
	   * @return boolean
	   */
	
	public static List<InputStream> readAllFileByFolderPath(String filepath) throws FileNotFoundException, IOException {
		
		List<InputStream> readAllFile = new FileUtil().readAllFile(filepath);
		
		return readAllFile;
	}

	
	/**
	 * Bas 通过文件双路径拷贝文件
	 */
	public boolean copyFileToFolder(String filePath, String distPath) {
		File file = new File(filePath);
		return this.copyFileToFolder(file, distPath);
	}
	/**
	 * Bas 通过文件，及文件路径拷贝文件
	 */
	public boolean copyFileToFolder(File file, String distPath) {
		logger.debug("file is {}, distPath is {}", file, distPath);
		try {
			//使用apache的FileUtils来复制文件，因为FileUtils已进行验证，所以在这里不再做验证
			File dist = new File(distPath);
			FileUtils.copyFile(file, new File(distPath));
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * Bas 获取目录集合
	 */
	public File[] getDirectoryList(String basePath){
		logger.debug("basePath is {}", basePath);
		File file = new File(basePath);
//		File files[] = file.listFiles(new DirectoryFilter());
//		return files;
		return null;
	}
	
	/**
	 * Bas 获取文件子集合
	 */
	public File[] getSubList(String basePath) {
		logger.debug("basePath is {}", basePath);
		File file = new File(basePath);
		File files[] = file.listFiles();
		return files;
	}
	/**
	 * Bas 判断文件是否存在
	 */
	public boolean isExist(String basePath, String fileName){
		basePath = FileUtil.getSafetyPath(basePath);
		System.out.println(basePath + fileName);
		File file = new File(basePath + fileName);
		return file.exists();
	}
	
	/**
	 
	 * 防止路径最后没有斜杠
	 * @param path
	 * @return String
	 */
	public static String getSafetyPath(String path){
		if (path == null)
			return null;
		if (path.endsWith("/") || path.endsWith("\\"))
			return path;
		else
			return path + getSlash();
	}
	
	/**
	 * 获取操作系统相关分隔符
	 * @return String
	 */
	public static String getSlash(){
		return System.getProperty("file.separator");
	}
	
	
	/**
	 * Bas 根据文件路径删除文件
	 * @return boolean
	 */
	public boolean deleteFile(String basePath) {
		if (basePath == null)
			return false;
		File file = new File(basePath);
		return file.delete();
	}
	
	
	public static String replaceInvaildChar(String str) {
		if (str == null)
			return null;
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(str);
		return matcher.replaceAll("_");
	}
	/**
	 * Bas 通过文件标识创建子文件夹
	 */
	public boolean createMeasurementFolderByContent(String Content, String root) {
		boolean success = true;
		if (StringUtils.isEmpty(root) || StringUtils.isEmpty(Content)) {
			success = false;
		} else {
			String path = FileUtil.getSafetyPath(root) + FileUtil.replaceInvaildChar(Content);
			File file = new File(path);
			logger.debug("path : {} , exists : {}", file.getPath(), file.exists());
			if (!file.exists()) {
				file.mkdirs();
			}
		}
		return success;
	}
	
	private List<InputStream> readAllFile(String folderpath) throws FileNotFoundException, IOException {
		
		List<InputStream> is = new ArrayList<InputStream>();
		
		try {
			File file = new File(folderpath);
			
			if (file.isDirectory()) {
				
				String[] filelist = file.list();
				
				for (int i = 0; i < filelist.length; i++) {
					String tmepPath = folderpath +  "/"+filelist[i];
					is.addAll(readAllFile(tmepPath));
				}
				
			}else {
				is.add(FileUtil.getInputStramByAbs(file.getPath()));
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return is;
	}
	
	
}
